import { defineStore } from 'pinia';
import {
  getCategory1ListApi,
  getCategory2ListApi,
  getCategory3ListApi,
} from '/@/api/product/category';
import type { CategoryDataModel } from '../types';

// 暴露useCategoryStore是一个函数
// 函数调用的返回值，就是对象，对象上面就是state数据和actions函数、getters数据等
export const useCategoryStore = defineStore('category', {
  // 数据
  state: (): CategoryDataModel => ({
    category1Id: undefined,
    category2Id: undefined,
    category3Id: undefined,
    category1List: [],
    category2List: [],
    category3List: [],
  }),
  // 只读的计算属性数据
  getters: {},
  // 原来vuex的actions+mutations
  // 发送请求并更新数据
  actions: {
    async getCategory1List() {
      this.category1List = await getCategory1ListApi();
    },
    async getCategory2List(category1Id: number) {
      this.category1Id = category1Id;
      this.category2List = await getCategory2ListApi(category1Id);
      // 清空
      this.category2Id = undefined;
      this.category3Id = undefined;
      this.category3List = [];
    },
    async getCategory3List(category2Id: number) {
      this.category2Id = category2Id;
      this.category3List = await getCategory3ListApi(category2Id);
      // 清空
      this.category3Id = undefined;
    },
  },
});
